package system

import (
	"MoSkeleton/models/base"
	"gorm.io/gorm"
	"strconv"
)

type SysUserRole struct {
	UserId uint64 `gorm:"column:user_id;type:BIGINT;NOT NULL"`
	RoleId uint64 `gorm:"column:role_id;type:BIGINT;NOT NULL"`
}

func (b *SysUserRole) TableName() string {
	return "sys_user_role"
}

func (b *SysUserRole) AddRoleUserIds(tx *gorm.DB, roleId uint64, userIds *[]string) (int64, error) {
	var userRoles []*SysUserRole
	for _, userId := range *userIds {
		uId, _ := strconv.ParseUint(userId, 10, 64)

		userRoles = append(userRoles, &SysUserRole{
			UserId: uId,
			RoleId: roleId,
		})
	}
	return b.AddBatch(tx, userRoles)
}

func (b *SysUserRole) AddUserRoleIds(tx *gorm.DB, userId uint64, roleIds *[]uint64) (int64, error) {
	var userRoles []*SysUserRole
	for _, roleId := range *roleIds {
		userRoles = append(userRoles, &SysUserRole{
			UserId: userId,
			RoleId: roleId,
		})
	}
	if len(userRoles) > 0 {
		return b.AddBatch(tx, userRoles)
	}
	return 0, nil
}
func (b *SysUserRole) AddBatch(tx *gorm.DB, userRoles []*SysUserRole) (int64, error) {
	result := base.GetModelDB(tx).Create(userRoles)
	return result.RowsAffected, result.Error
}

func (b *SysUserRole) Delete(tx *gorm.DB, userId uint64, roleId uint64) (bool, error) {
	result := base.GetModelDB(tx).Where("user_id = ? and role_id = ?", userId, roleId).Delete(b)
	return result.RowsAffected > 0, result.Error
}

func (b *SysUserRole) DeleteByRoleUserIds(tx *gorm.DB, roleId uint64, userIds *[]string) (bool, error) {
	result := base.GetModelDB(tx).Where("role_id = ? and user_id in (?)", roleId, *userIds).Delete(b)
	return result.RowsAffected > 0, result.Error
}
func (b *SysUserRole) DeleteByUserId(tx *gorm.DB, userId uint64) (bool, error) {
	result := base.GetModelDB(tx).Where("user_id = ?", userId).Delete(b)
	return result.RowsAffected > 0, result.Error
}

func (b *SysUserRole) DeleteByUserIds(tx *gorm.DB, userIds *[]uint64) (bool, error) {
	result := base.GetModelDB(tx).Where("user_id in (?)", *userIds).Delete(b)
	return result.RowsAffected > 0, result.Error
}
